<template>
  <div class="container">
    <el-row :gutter="10">
      <el-col :span="24">
        <div class="section" style="background: white; border-radius: 10px; margin: 10px; padding: 20px;">
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="http://192.168.0.47:5001"
              :file-list="preFacingAudio.video"
              accept="video/*"
              :auto-upload="true"
              :on-change="handleChangeVideo"
          >
            <template #trigger>
              <el-button type="primary">选择视频文件</el-button>
            </template>
            <div style="margin-top: 10px;">
              <span v-if="!videoFile" style="color: #999">未选择文件</span>
            </div>
          </el-upload>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="24">
        <div class="section" style="background: white; border-radius: 10px; margin: 10px;">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="video-container">
                <h3>原视频</h3>
                <el-button
                    type="primary"
                    style="margin-bottom: 10px;"
                    @click="removeWatermark"
                    :loading="isLoading"
                    :disabled="!videoFile"
                >
                  去除时间日期
                </el-button>
                <video v-if="originalVideoSrc" controls style="width: 100%; max-height: 400px;">
                  <source :src="originalVideoSrc" type="video/mp4">
                  您的浏览器不支持视频标签。
                </video>
                <div v-else class="video-placeholder">
                  <el-empty description="请先上传视频"></el-empty>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="video-container">
                <h3>去修改</h3>
                <div v-if="processedVideoSrc" class="result-container">
                  <el-button
                      type="success"
                      style="margin-top: 10px;"
                      @click="downloadVideo"
                  >
                    下载处理后的视频
                  </el-button>
                  <video controls style="width: 100%; max-height: 400px;">
                    <source :src="processedVideoSrc" type="video/mp4">
                    您的浏览器不支持视频标签。
                  </video>
                </div>
                <div v-else class="placeholder">
                  <el-empty description="处理后视频将显示在这里"></el-empty>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';

// 加载 opencv.js
onMounted(async () => {

});

const ffmpeg = createFFmpeg({
  log: true,
  corePath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.js',
  mainName: 'main',
  workerPath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.worker.js',
  wasmPath: 'https://unpkg.com/@ffmpeg/core@0.11.0/dist/ffmpeg-core.wasm'
});

const originalVideoSrc = ref('');
const processedVideoSrc = ref('');
const isLoading = ref(false);
const videoFile = ref<File | null>(null);
const processedBlob = ref<Blob | null>(null);

const preFacingAudio = reactive({
  video: [] as any[],
  subtitles: '',
  audio_file: [] as any[],
})

const handleChangeVideo = (file: any, fileList: any[]) => {
  console.log('File changed:', file, fileList)
  preFacingAudio.video = fileList
  if (preFacingAudio.video.length > 0) {
    videoFile.value = file.raw; // 修改: 使用 file.raw 获取文件对象
    originalVideoSrc.value = URL.createObjectURL(file.raw); // 修改: 使用 file.raw 获取文件对象
  }
}

const downloadVideo = () => {
  if (!processedBlob.value) return;

  const url = URL.createObjectURL(processedBlob.value);
  const a = document.createElement('a');
  a.href = url;
  a.download = `processed_${videoFile.value?.name || 'video.mp4'}`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const detectWatermarkPosition = async (video: HTMLVideoElement): Promise<{ x: number, y: number, w: number, h: number } | null> => {
  return new Promise(async (resolve) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx) return resolve(null);

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    console.log(imageData);

    // 使用Tesseract.js或者其他OCR工具识别图像中的文字（例如日期时间）
    // 假设通过OCR识别到时间日期的区域为以下示例（你需要根据OCR结果动态获取这个位置）
    const watermarkPosition = await getWatermarkPositionFromOCR(imageData); // 用OCR函数来获取真实的水印位置

    // 如果未找到水印位置，返回null
    if (!watermarkPosition) return resolve(null);

    // 通过图像填充或模糊技术覆盖水印区域
    ctx.fillStyle = 'white'; // 或者填充为背景色
    ctx.fillRect(watermarkPosition.x, watermarkPosition.y, watermarkPosition.w, watermarkPosition.h);

    // 返回修改后的图片数据或视频帧
    resolve(watermarkPosition);
  });
};
// 模拟的OCR识别函数，用于识别水印或日期时间区域
const getWatermarkPositionFromOCR = async (imageData: ImageData): Promise<{ x: number, y: number, w: number, h: number } | null> => {
  // 实际上，OCR会返回一个定位区域
  // 这里你可以用像Tesseract.js来提取实际的文本并进行位置识别
  // 这里只是一个示例位置
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ x: 100, y: 100, w: 200, h: 50 }); // 你需要根据OCR实际结果来更新此部分
    }, 500);
  });
};
const removeWatermark = async () => {
  if (!videoFile.value) return;

  isLoading.value = true;

  try {
    const video = document.createElement('video');
    video.src = URL.createObjectURL(videoFile.value);
    video.preload = 'metadata';

    video.onloadedmetadata = async () => {
      video.width = video.videoWidth;
      video.height = video.videoHeight;

      const watermarkPosition = await detectWatermarkPosition(video);
      console.log(watermarkPosition)
      if (!watermarkPosition) {
        ElMessage.error('无法检测到时间日期区域');
        isLoading.value = false;
        return;
      }

      await ffmpeg.load();
      ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(videoFile.value));

      // 使用 FFmpeg 去除检测到的时间日期区域
      await ffmpeg.run(
        '-i', 'input.mp4',
        '-vf', `delogo=x=${watermarkPosition.x}:y=${watermarkPosition.y}:w=${watermarkPosition.w}:h=${watermarkPosition.h}`,
        'output.mp4'
      );

      const data = ffmpeg.FS('readFile', 'output.mp4');
      processedBlob.value = new Blob([data.buffer], { type: 'video/mp4' });
      processedVideoSrc.value = URL.createObjectURL(processedBlob.value);

      isLoading.value = false;
    };
  } catch (error) {
    console.error('Error removing watermark:', error);
    ElMessage.error('去水印失败');
    isLoading.value = false;
  }
};

</script>

<style scoped>
.container {
  padding: 10px;
}

.section {
  padding: 20px;
}

.video-container {
  text-align: center;
  height: 100%;
}

.result-container {
  border: 2px dashed #67c23a;
  border-radius: 8px;
  padding: 10px;
  margin-top: 10px;
}

.placeholder, .video-placeholder {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #f5f7fa;
}

video {
  background-color: #000;
}
</style>